/**
 * 
 */
package com.infodms.dms.actions.sales.ordermanage.delivery;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;

import com.infodms.dms.bean.AclUserBean;
import com.infodms.dms.common.Constant;
import com.infodms.dms.common.ErrorCodeConstant;
import com.infodms.dms.common.getCompanyId.GetOemcompanyId;
import com.infodms.dms.common.materialManager.MaterialGroupManagerDao;
import com.infodms.dms.dao.common.VerFlagDao;
import com.infodms.dms.dao.sales.financemanage.AccountBalanceDetailDao;
import com.infodms.dms.dao.sales.ordermanage.delivery.OrderDeliveryDao;
import com.infodms.dms.dao.sales.ordermanage.orderreport.OrderReportDao;
import com.infodms.dms.exception.BizException;
import com.infodms.dms.po.TmBusinessAreaPO;
import com.infodms.dms.po.TmDateSetPO;
import com.infodms.dms.po.TtVsDlvryPO;
import com.infodms.dms.po.TtVsDlvryReqDtlPO;
import com.infodms.dms.po.TtVsDlvryReqPO;
import com.infodms.dms.po.TtVsOrderDetailPO;
import com.infodms.dms.po.TtVsOrderPO;
import com.infodms.dms.po.TtVsOrderResourceReservePO;
import com.infodms.dms.util.DateTimeUtil;
import com.infodms.dms.util.businessUtil.ReqLogUtil;
import com.infoservice.mvc.context.ActionContext;
import com.infoservice.mvc.context.RequestWrapper;
import com.infoservice.po3.bean.PO;
import com.infoservice.po3.bean.PageResult;
import static com.infodms.dms.actions.sales.financemanage.AccountOpera.* ;

/**
 * @author Administrator
 * 
 */
public class DeliveryCommandCancel {

	public Logger logger = Logger.getLogger(DeliveryCommandCancel.class);
	private final OrderDeliveryDao dao = OrderDeliveryDao.getInstance();
	private final AccountBalanceDetailDao accoutDao = AccountBalanceDetailDao.getInstance();
	private final OrderReportDao reportDao = OrderReportDao.getInstance();
	private ActionContext act = ActionContext.getContext();
	RequestWrapper request = act.getRequest();
	private final String initUrl = "/jsp/sales/ordermanage/delivery/deliveryCommandCancelQuery.jsp";
	private final String qinfoUrl = "/jsp/sales/ordermanage/delivery/deliveryCommandCancelInfo.jsp";

	/**
	 * 发运指令取消页面初始化
	 */
	public void deliveryCommandCancelInit() {
		AclUserBean logonUser = (AclUserBean) act.getSession().get(Constant.LOGON_USER);
		try {
			Long oemCompanyId = GetOemcompanyId.getOemCompanyId(logonUser);
			TmDateSetPO dateSet = reportDao.getTmDateSetPO(new java.util.Date(), oemCompanyId);
			String dateStr = DateTimeUtil.parseDateToDate(new Date());
			act.setOutData("year", dateSet != null ? dateSet.getSetYear() : "");
			act.setOutData("week", dateSet != null ? dateSet.getSetWeek() : "");
			act.setOutData("dateStr", dateStr);
			act.setForword(initUrl);
		} catch (Exception e) {// 异常方法
			BizException e1 = new BizException(act, e, ErrorCodeConstant.QUERY_FAILURE_CODE,
					"发运指令取消初始化");
			logger.error(logonUser, e1);
			act.setException(e1);
		}
	}

	/**
	 * 发运指令取消查询
	 */
	public void deliveryCommandCancelQuery() {
		AclUserBean logonUser = (AclUserBean) act.getSession().get(Constant.LOGON_USER);
		try {
			String startYear = request.getParamValue("startYear"); // 订单起始年
			String endYear = request.getParamValue("endYear"); // 订单结束年
			String startWeek = request.getParamValue("startWeek"); // 订单起始周
			String endWeek = request.getParamValue("endWeek"); // 订单结束周
			String startDate = request.getParamValue("startDate"); // 发运起始时间
			String endDate = request.getParamValue("endDate"); // 发运结束时间
			String orderType = request.getParamValue("orderType"); // 订单类型
			String orderNo = request.getParamValue("orderNo"); // 订单号码
			String transportType = request.getParamValue("transportType"); // 运送方式
			String deliveryStatus = request.getParamValue("deliveryStatus");// 发运状态
			String groupCode = request.getParamValue("groupCode"); // 物料组CODE
			String dealerCode = request.getParamValue("dealerCode"); // 经销商CODE
			Long companyId = logonUser.getCompanyId();
			Integer curPage = request.getParamValue("curPage") != null ? Integer.parseInt(request
					.getParamValue("curPage")) : 1;
			List<Map<String, Object>> areaList = MaterialGroupManagerDao
					.getPoseIdBusiness(logonUser.getPoseId().toString());
			String areaIds = "";
			if (areaList.size() > 0) {
				for (int i = 0; i < areaList.size(); i++) {
					if ("".equals(areaIds)) {
						areaIds = areaList.get(i).get("AREA_ID").toString();
					} else {
						areaIds = areaList.get(i).get("AREA_ID").toString() + "," + areaIds;
					}
				}

			}
			PageResult<Map<String, Object>> ps = dao.getDeliveryCommandCancelQueryList(startYear,
					startWeek, endYear, endWeek, startDate, endDate, orderType, dealerCode,
					orderNo, transportType, deliveryStatus, groupCode, areaIds, companyId, curPage,
					Constant.PAGE_SIZE);
			act.setOutData("ps", ps);
		} catch (Exception e) {// 异常方法
			BizException e1 = new BizException(act, e, ErrorCodeConstant.QUERY_FAILURE_CODE,
					"发运指令取消查询");
			logger.error(logonUser, e1);
			act.setException(e1);
		}
	}

	public void deliveryCommandCancelInfo() {
		AclUserBean logonUser = (AclUserBean) act.getSession().get(Constant.LOGON_USER);
		try {
			String reqId = request.getParamValue("reqId");
			String orderType = request.getParamValue("orderType");
			Long companyId = GetOemcompanyId.getOemCompanyId(logonUser);
			Map<String, Object> map = dao.getdeliveryInfoMap(reqId);
			String areaGet = ((BigDecimal) map.get("AREA_ID")).toString();
			
			TmBusinessAreaPO areaPO = new TmBusinessAreaPO();
			areaPO.setAreaId(new Long(areaGet));
			List<PO> areaList = dao.select(areaPO);
			Long erpCode = null;
			if(areaList.size() != 0){
				areaPO = (TmBusinessAreaPO)areaList.get(0);
				erpCode = areaPO.getErpCode();
			}
			
			List<Map<String, Object>> list = dao.getorderResourceReserveDetailList(reqId,
					orderType, String.valueOf(companyId), erpCode.toString());
			BigDecimal dealerId = (BigDecimal) map.get("BILLING_ORG_ID");
			List<Map<String, Object>> discountList = accoutDao
					.getDiscountAccountInfoByDealerId(dealerId.toString());
			act.setOutData("map", map);
			act.setOutData("list", list);
			act.setOutData("discountList", discountList);
			act.setForword(qinfoUrl);
		} catch (Exception e) {// 异常方法
			BizException e1 = new BizException(act, e, ErrorCodeConstant.QUERY_FAILURE_CODE,
					"发运指令取消");
			logger.error(logonUser, e1);
			act.setException(e1);
		}
	}

	public void deliveryCommandCancel() {
		AclUserBean logonUser = (AclUserBean) act.getSession().get(Constant.LOGON_USER);
		try {
			String reqVer = request.getParamValue("reqVer");// 发运申请版本号
			String deliveryId = request.getParamValue("deliveryId");// 发运单ID
			String orderId = request.getParamValue("orderId"); // 订单ID
			String reqId = request.getParamValue("reqId"); // 发运申请ID
			String orderType = request.getParamValue("orderType"); // 订单类型
			String returnValue = "1";

			boolean verFlag = true;
			verFlag = VerFlagDao.getVerFlag("TT_VS_DLVRY_REQ", "REQ_ID", reqId, reqVer);
			if (verFlag) {
				// 发运单更新
				TtVsDlvryPO tvdp1 = new TtVsDlvryPO();
				tvdp1.setDeliveryId(new Long(deliveryId));
				TtVsDlvryPO tvdp2 = new TtVsDlvryPO();
				tvdp2.setDeliveryStatus(Constant.DELIVERY_STATUS_09);// 已取消
				tvdp2.setUpdateBy(logonUser.getUserId());
				tvdp2.setUpdateDate(new Date(System.currentTimeMillis()));
				dao.update(tvdp1, tvdp2);

				// 发运申请更新
				TtVsDlvryReqPO tvdrp1 = new TtVsDlvryReqPO();
				tvdrp1.setReqId(new Long(reqId));
				TtVsDlvryReqPO tvdrp2 = new TtVsDlvryReqPO();
				tvdrp2.setReqStatus(Constant.ORDER_REQ_STATUS_07);// 已取消
				tvdrp2.setVer(new Integer(Integer.parseInt(reqVer) + 1));
				tvdrp2.setUpdateBy(logonUser.getUserId());
				tvdrp2.setUpdateDate(new Date(System.currentTimeMillis()));
				dao.update(tvdrp1, tvdrp2);

				TtVsDlvryReqDtlPO tvdrdp = new TtVsDlvryReqDtlPO();
				tvdrdp.setReqId(new Long(reqId));
				List<TtVsDlvryReqDtlPO> reqDtlList = dao.select(tvdrdp);
				// 释放保留资源
				for (int i = 0; i < reqDtlList.size(); i++) {
					tvdrdp = reqDtlList.get(i);
					TtVsOrderResourceReservePO tvorrp1 = new TtVsOrderResourceReservePO();
					tvorrp1.setReqDetailId(tvdrdp.getDetailId());
					TtVsOrderResourceReservePO tvorrp2 = new TtVsOrderResourceReservePO();
					tvorrp2.setReserveStatus(Constant.RESOURCE_RESERVE_STATUS_02);// 已取消
					dao.update(tvorrp1, tvorrp2);

					// 常规订单更新订单明细
					if (Integer.parseInt(orderType) == Constant.ORDER_TYPE_01.intValue()) {
						TtVsOrderDetailPO tvodp = reportDao.getTtSalesOrderDetail(tvdrdp.getOrderDetailId().toString());

						TtVsOrderDetailPO tvodp1 = new TtVsOrderDetailPO();
						tvodp1.setDetailId(tvodp.getDetailId());
						TtVsOrderDetailPO tvodp2 = new TtVsOrderDetailPO();
						tvodp2.setCallAmount(tvodp.getCallAmount().intValue() - tvdrdp.getReqAmount().intValue());
						tvodp2.setUpdateBy(logonUser.getUserId());
						tvodp2.setUpdateDate(new Date(System.currentTimeMillis()));
						dao.update(tvodp1, tvodp2) ;
					}
				}

				// 非常规订单更新订单
				if (Integer.parseInt(orderType) != Constant.ORDER_TYPE_01.intValue()) {
					TtVsOrderPO tvop1 = new TtVsOrderPO();
					tvop1.setOrderId(new Long(orderId));
					TtVsOrderPO tvop2 = new TtVsOrderPO();
					tvop2.setOrderStatus(Constant.ORDER_STATUS_06);// 已取消
					tvop2.setUpdateBy(logonUser.getUserId());
					tvop2.setUpdateDate(new Date(System.currentTimeMillis()));
					dao.update(tvop1, tvop2);
				}
				
				// 释放资金
				dmsReleasePrice(reqId, logonUser.getUserId().toString());
				/*// 释放资金
				AccountBalanceDetailDao dao = AccountBalanceDetailDao.getInstance();
				dao.releaseAllFreezeAmountByReqId(reqId, logonUser.getUserId().toString());*/
				
				//向发运申请操作日志表写入日志信息
				ReqLogUtil.creatReqLog(Long.parseLong(reqId), Constant.REQ_LOG_TYPE_09, logonUser.getUserId());
				
				//同步结算中心下级经销商订单
				AccountBalanceDetailDao.getInstance().
					syncOrderToDFS(Long.parseLong(orderId), true, logonUser.getUserId(), true);
			} else {
				returnValue = "2";
			}
			act.setOutData("returnValue", returnValue);
		} catch(RuntimeException e) {
			BizException e1 = new BizException(act,e,ErrorCodeConstant.PUTIN_FAILURE_CODE,e.getMessage());
			logger.error(logonUser,e1);
			act.setException(e);
		} catch (Exception e) {// 异常方法
			BizException e1 = new BizException(act, e, ErrorCodeConstant.SAVE_FAILURE_CODE,
					"订单资源审核保存");
			logger.error(logonUser, e1);
			act.setException(e1);
		}
	}
}
